package com.sdy.dcsb.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sdy.common.model.Response;
import com.sdy.dcsb.biz.model.EsbConsumerSystem;
import com.sdy.dcsb.biz.model.EsbConsumerSystemJoint;
import com.sdy.dcsb.biz.model.EsbConsumerTree;
import com.sdy.dcsb.biz.service.EsbConsumerSystemService;
import com.sdy.dcsb.biz.service.EsbConsumerTreeService;
import com.sdy.dcsb.biz.service.UserOperationLogService;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;
import static org.springframework.util.StringUtils.isEmpty;

/**
 * <p>
 * 服务消费者树表 前端控制器
 * </p>
 *
 * @author fb
 * @since 2019-09-25
 */
@Slf4j
@Controller
@RequestMapping("/EsbConsumerSystem")
@Api(tags = "消费者系统相关接口")
public class EsbConsumerSystemController extends BaseController {
    @Autowired
    private EsbConsumerSystemService esbConsumerSystemService;
    @Autowired
    private EsbConsumerTreeService esbConsumerTreeService;
    @Autowired
    private UserOperationLogService userOperationLogService;

    /**
     * 查询树目录下的系统
     * @param id 主键,当前节点id
     * @param current ,当前页
     * @param size ,每页数量
     * @param type 查询类别,1:系统名称 2:系统编码 其他:查全部
     * @param message ,查询值
     * @return
     */
    @GetMapping("/selectSubSystemById")
    @ResponseBody
    @ApiOperation("查询树目录下的系统，分页，可按系统编码或系统名称模糊查询,id必传")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前节点id"),
            @ApiImplicitParam(dataType = "Integer", name = "current", value = "当前页"),
            @ApiImplicitParam(dataType = "Integer", name = "size", value = "每页数量"),
            @ApiImplicitParam(dataType = "Integer", name = "type", value = "查询类别,1:系统名称 2:系统编码 其他:查全部"),
            @ApiImplicitParam(dataType = "String", name = "message", value = "查询值"),
    })
    public Response selectSubSystemById(Integer id, Integer current, Integer size, Integer type, String message) {
        if(isEmpty(id)) {
            return Response.error("请求id不能为空");
        }
        JSONObject object = new JSONObject();
        if(isEmpty(current)) {
            current = 1;
        }
        if(isEmpty(size)) {
            size = 10;
        }
        object.put("size",size);
        object.put("current",current);
        object.put("searchCount",true);

        Integer total = 0;
        Integer page = 0;

        if(!isEmpty(message)) {
            try {
                message = URLDecoder.decode(message,"utf-8");
            }catch(IOException e) {

            }
            if(isEmpty(type)){
                return Response.error("查询类别不能为空");
            }
            if(type.equals(1)) {
                List<EsbConsumerSystemJoint> resultCount = esbConsumerSystemService.findCountSystemByIdType(id,"system_name", message);
                total = resultCount.size();
                if(total%size==0){
                    page = total/size;
                }else {
                    page = total/size+1;
                }
                List<EsbConsumerSystemJoint> result = esbConsumerSystemService.findSubSystemByIdType(id, current, size,"system_name", message);
                object.put("records",result);
                object.put("total",total);
                object.put("pages",page);
            }else if(type.equals(2)) {
                List<EsbConsumerSystemJoint> resultCount = esbConsumerSystemService.findCountSystemByIdType(id,"system_code", message);
                total = resultCount.size();
                if(total%size==0){
                    page = total/size;
                }else {
                    page = total/size+1;
                }
                List<EsbConsumerSystemJoint> result = esbConsumerSystemService.findSubSystemByIdType(id, current, size,"system_code",  message);
                object.put("records",result);
                object.put("total",total);
                object.put("pages",page);
            }else {
                List<EsbConsumerSystemJoint> resultCount = esbConsumerSystemService.findCountSystemById(id);
                total = resultCount.size();
                if(total%size==0){
                    page = total/size;
                }else {
                    page = total/size+1;
                }
                List<EsbConsumerSystemJoint> result = esbConsumerSystemService.findSubSystemById(id, current, size);
                object.put("records",result);
                object.put("total",total);
                object.put("pages",page);
                return Response.success(object);
            }
        }else {
            List<EsbConsumerSystemJoint> resultCount = esbConsumerSystemService.findCountSystemById(id);
            total = resultCount.size();
            if(total%size==0){
                page = total/size;
            }else {
                page = total/size+1;
            }
            List<EsbConsumerSystemJoint> result = esbConsumerSystemService.findSubSystemById(id, current, size);
            object.put("records",result);
            object.put("total",total);
            object.put("pages",page);
        }
        return Response.success(object);
    }

    /**
     * 查询单条系统数据
     * @param id ,系统id
     * @return
     */
    @GetMapping("/select")
    @ResponseBody
    @ApiOperation("查询单条系统数据")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前系统id"),
    })
    public Response select(Integer id) {
        if(!isEmpty(id)) {
            return Response.success(esbConsumerSystemService.getById(id));
        }else {
            return Response.error("请求id不能为空");
        }
    }

    /**
     * 从树目录查询单条系统数据
     * @param code ,系统id
     * @return
     */
    @GetMapping("/selectSystem")
    @ResponseBody
    @ApiOperation("从树目录查询单条系统数据,haschildren=0时调用此接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "code", value = "系统id"),
    })
    public Response selectSystem(String code) {
        if(!isEmpty(code)) {
            try {
                code = URLDecoder.decode(code,"utf-8");
            }catch(IOException e) {

            }
            return Response.success(esbConsumerSystemService.getById(code));
        }else {
            return Response.error("查询的消费者系统id不能为空");
        }

    }

    /**
     * 修改单条系统信息
     * @param id ,当前系统id
     * @param systemName ,系统名称
     * @param pName ,系统联系人
     * @param pPhone ,手机/电话号码/QQ
     * @param manageName ,管理部门
     * @return
     */
    @GetMapping("/update")
    @ResponseBody
    @ApiOperation("修改单条系统信息，系统编码不可修改")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前系统id"),
            @ApiImplicitParam(dataType = "String", name = "systemName", value = "系统名称"),
            @ApiImplicitParam(dataType = "String", name = "pName", value = "系统联系人"),
            @ApiImplicitParam(dataType = "String", name = "pPhone", value = "手机/电话号码/QQ"),
            @ApiImplicitParam(dataType = "String", name = "manageName", value = "管理部门"),
    })
    public Response update(HttpServletRequest request, Integer id, String systemName, String pName, String pPhone, String manageName) {
        if(isEmpty(id)) {
            return Response.error("请求id不能为空");
        }
        try {
            if(!isEmpty(systemName)) {
                systemName = URLDecoder.decode(systemName,"utf-8");
            }
            if(!isEmpty(pName)) {
                pName = URLDecoder.decode(pName,"utf-8");
            }
            if(!isEmpty(pPhone)) {
                pPhone = URLDecoder.decode(pPhone,"utf-8");
            }
            if(!isEmpty(manageName)) {
                manageName = URLDecoder.decode(manageName,"utf-8");
            }

        }catch(IOException e) {
            log.error(e.getMessage());
        }

        if(!isEmpty(systemName)) {
            QueryWrapper<EsbConsumerSystem> wrapper = new QueryWrapper<>();
            wrapper.eq("id", id);
            List<EsbConsumerSystem> result = esbConsumerSystemService.list(wrapper);
            if(result.size() == 0) {
                return Response.error("请求的id有误，无法查询到数据");
            }
            EsbConsumerSystem esbConsumerSystem = new EsbConsumerSystem();
            EsbConsumerTree esbConsumerTree = new EsbConsumerTree();

            Integer i = 0;
            Integer j = 0;

            if(!isEmpty(result.get(0).getSystemName())) {
                if(!result.get(0).getSystemName().equals(systemName)) {
                    esbConsumerSystem.setSystemName(systemName);
                    i++;
                    esbConsumerTree.setName(systemName);
                    j++;
                }
            }else {
                if(!isEmpty(systemName)) {
                    esbConsumerSystem.setSystemName(systemName);
                    i++;
                    esbConsumerTree.setName(systemName);
                    j++;
                }
            }
            if(!isEmpty(result.get(0).getPName())) {
                if(!result.get(0).getPName().equals(pName)){
                    if(!isEmpty(pName)) {
                        esbConsumerSystem.setPName(pName);
                        i++;
                    }else {
                        esbConsumerSystem.setPName("");
                        i++;
                    }
                }
            }else {
                if(!isEmpty(pName)) {
                    esbConsumerSystem.setPName(pName);
                    i++;
                }
            }
            if(!isEmpty(result.get(0).getPPhone())) {
                if(!result.get(0).getPPhone().equals(pPhone)){
                    if(!isEmpty(pPhone)) {
                        esbConsumerSystem.setPPhone(pPhone);
                        i++;
                    }else {
                        esbConsumerSystem.setPPhone("");
                        i++;
                    }

                }
            }else {
                if(!isEmpty(pPhone)) {
                    esbConsumerSystem.setPPhone(pPhone);
                    i++;
                }
            }
            if(!isEmpty(result.get(0).getManageName())) {
                if(!result.get(0).getManageName().equals(manageName)){
                    if(!isEmpty(manageName)) {
                        esbConsumerSystem.setManageName(manageName);
                        i++;
                    }else {
                        esbConsumerSystem.setManageName("");
                        i++;
                    }
                }
            }else {
                if(!isEmpty(manageName)) {
                    esbConsumerSystem.setManageName(manageName);
                    i++;
                }
            }

            if(i >= 1) {
                userOperationLogService.savaUserLog(request, "修改消费者系统信息：" +
                        esbConsumerSystemService.getById(id).getSystemName());
                boolean type = esbConsumerSystemService.update(esbConsumerSystem, new UpdateWrapper<EsbConsumerSystem>().eq("id", id));
                if(type) {
                    if(j >= 1){
                        userOperationLogService.savaUserLog(request, "修改消费者树目录信息：" +
                                esbConsumerSystemService.getById(id).getSystemName() + "--->" + systemName);
                        boolean treeType = esbConsumerTreeService.update(esbConsumerTree, new UpdateWrapper<EsbConsumerTree>().eq("code",id));
                        if(treeType){

                        }else {
                            return Response.error("树信息修改失败");
                        }
                    }
                    return Response.success("信息修改成功");
                }else {
                    return Response.error("信息修改失败");
                }
            }else {
                return Response.error("信息无变化");
            }

        }else {
            return Response.error("系统名称不能为空");
        }
    }

    /**
     * 删除单条系统数据
     * @param id ,当前系统id
     * @return
     */
    @GetMapping("/delete")
    @ResponseBody
    @ApiOperation("删除单条系统数据")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前系统id"),
    })
    public Response delete(HttpServletRequest request, Integer id) {
        if(!isEmpty(id)) {
            String name = esbConsumerSystemService.getById(id).getSystemName();
            userOperationLogService.savaUserLog(request, "删除消费者系统信息：" + name);
            if(esbConsumerSystemService.removeById(id)) {
                QueryWrapper<EsbConsumerTree> wrapper = new QueryWrapper<>();
                wrapper.eq("code", id);
                userOperationLogService.savaUserLog(request, "删除消费者树目录信息：" + name);
                if(esbConsumerTreeService.remove(wrapper)) {
                    return Response.success("删除消费者系统成功");
                }else {
                    return Response.error("删除消费者树目录失败!");
                }
            }else {
                return Response.error("删除消费者系统失败!");
            }
        }else {
            return Response.error("请求id不能为空");
        }
    }

    /**
     * 节点目录下新增系统
     * @param id ,当前节点id
     * @param lvl ,节点层级
     * @param haschildren ,当前节点有无子节点 1:有,0:无
     * @param systemName ,系统名称
     * @param systemCode ,系统编码
     * @param pName ,系统联系人
     * @param pPhone ,手机/电话号码/QQ
     * @param manageName ,管理部门
     * @return
     */
    @GetMapping("/insert")
    @ResponseBody
    @ApiOperation("节点目录下新增系统")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前节点id"),
            @ApiImplicitParam(dataType = "Integer", name = "lvl", value = "节点层级"),
            @ApiImplicitParam(dataType = "Integer", name = "haschildren", value = "当前节点有无子节点 1:有,0:无"),
            @ApiImplicitParam(dataType = "String", name = "systemName", value = "系统名称"),
            @ApiImplicitParam(dataType = "String", name = "systemCode", value = "系统编码"),
            @ApiImplicitParam(dataType = "String", name = "pName", value = "系统联系人"),
            @ApiImplicitParam(dataType = "String", name = "pPhone", value = "手机/电话号码/QQ"),
            @ApiImplicitParam(dataType = "String", name = "manageName", value = "管理部门"),
    })
    public Response insert(HttpServletRequest request, Integer id, Integer lvl, Integer haschildren, String systemName,
                           String systemCode, String pName, String pPhone, String manageName) {
        if(isEmpty(id)) {
            return Response.error("请求id不能为空");
        }
        if(isEmpty(lvl)) {
            return Response.error("请求的节点层级不能为空");
        }
        if(isEmpty(systemCode)) {
            return Response.error("新增的系统编码不能为空");
        }
        if(isEmpty(systemName)) {
            return Response.error("新增的系统名称不能为空");
        }
        if (haschildren == 1) {
            try {
                systemName = URLDecoder.decode(systemName,"utf-8");
                systemCode = URLDecoder.decode(systemCode,"utf-8");
                if(!isEmpty(pName)) {
                    pName = URLDecoder.decode(pName,"utf-8");
                }
                if(!isEmpty(pPhone)) {
                    pPhone = URLDecoder.decode(pPhone,"utf-8");
                }
                if(!isEmpty(manageName)) {
                    manageName = URLDecoder.decode(manageName,"utf-8");
                }
            }catch(IOException e) {
                log.info("URLDecoder解码失败");
            }
            QueryWrapper<EsbConsumerSystem> esbConsumerSystemQueryWrapper = new QueryWrapper<>();
            esbConsumerSystemQueryWrapper.eq("system_code", systemCode);
            List<EsbConsumerSystem> esbConsumerSystemResult = esbConsumerSystemService.list(esbConsumerSystemQueryWrapper);
            if(esbConsumerSystemResult.size() != 0) {
                return Response.error("此消费者系统编码重复，请重新输入");
            }
            EsbConsumerSystem esbConsumerSystem = new EsbConsumerSystem();
            esbConsumerSystem.setSystemName(systemName);
            esbConsumerSystem.setSystemCode(systemCode);
            esbConsumerSystem.setPName(pName);
            esbConsumerSystem.setPPhone(pPhone);
            esbConsumerSystem.setManageName(manageName);
            esbConsumerSystem.setStatus("1");
            if(esbConsumerSystemService.save(esbConsumerSystem)){
                userOperationLogService.savaUserLog(request, "新增消费者系统信息：" + systemName);
                EsbConsumerTree esbConsumerTree = new EsbConsumerTree();
                esbConsumerTree.setCode(esbConsumerSystem.getId());
                esbConsumerTree.setHaschildren(0);
                esbConsumerTree.setLvl(lvl+1);
                esbConsumerTree.setName(systemName);
                esbConsumerTree.setStatus("1");
                esbConsumerTree.setParId(id);
                if(esbConsumerTreeService.save(esbConsumerTree)) {
                    userOperationLogService.savaUserLog(request, "新增消费者系统信息：" + systemName);
                    return Response.success("新增消费者和目录成功");
                }
                esbConsumerSystemService.removeById(esbConsumerSystem.getId());
                return Response.error("新建目录失败");
            }
            return Response.error("新增消费者失败");
        }
        return Response.error("当前目录下不能新增目录");
    }

    /**
     * 查询所有消费者系统数据，不分页
     * @return
     */
    @GetMapping("/selectAllSystem")
    @ResponseBody
    @ApiOperation("查询所有消费者系统数据，不分页")
    @ApiImplicitParams({
    })
    public Response selectAllSystem() {
        QueryWrapper<EsbConsumerSystem> esbConsumerSystemWrapper = new QueryWrapper<>();
        esbConsumerSystemWrapper.orderByAsc("id");
        List<EsbConsumerSystem> esbConsumerSystemResult = esbConsumerSystemService.list(esbConsumerSystemWrapper);
        return Response.success(esbConsumerSystemResult);
    }

}
